from flask import render_template, g, redirect, request, jsonify, current_app, abort

from info import constants, db
from info.models import Category, News, User
from info.modules.profile import profile_blu
from info.utils.common import query_user_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@profile_blu.route('/other_news_list')
def other_news_list():
    """
    其他用户的发布的新闻展示
    :return:
    """
    # 1 获取参数
    page = request.args.get("page", 1)
    user_id = request.args.get("user_id")

    # 2 判断参数
    try:
        page = int(page)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not all([page, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        other = User.query.get(user_id)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    if not other:
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = other.news_list.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []
    for news_item in news_li:
        news_dict_li.append(news_item.to_basic_dict())

    data = {
        "news_list": news_dict_li,
        "current_page": current_page,
        "total_page": total_page,

    }
    return jsonify(errno=RET.OK, errmsg="操作成功", data=data)


@profile_blu.route('/other_info')
@query_user_data
def other_info():
    """
    其他用户的数据展示
    :return:
    """
    user = g.user
    # 获取 id
    other_id = request.args.get("user_id")

    # 判断参数
    try:
        other_id = int(other_id)
    except Exception as f:
        current_app.logger.error(f)
    if not other_id:
        abort(404)

    try:
        other = User.query.get(other_id)
    except Exception as f:
        current_app.logger.error(f)

    if not other:
        abort(404)
    is_followed = False
    # 如果新闻有作者,和用户
    if other and user:
        # 这个新闻在这个用户的关注中
        if other in user.followed:
            is_followed = True

    data = {
        "user": g.user.to_dict() if g.user else None,
        "other_info": other.to_dict(),
        "is_followed": is_followed
    }
    return render_template("news/other.html", data=data)


@profile_blu.route('/user_follow')
@query_user_data
def user_follow():
    """
    用户个人中心的关注列表显示
    :return:
    """
    # 1 获取参数
    p = request.args.get("p", 1)

    # 2 检验参数
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    try:
        p = int(p)
    except Exception as f:
        current_app.logger.error(f)

    # 3 查询数据库
    follow_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        follow_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as f:
        current_app.logger.error(f)

    follow_dict_li = []
    for followed_user in follow_li:
        follow_dict_li.append(followed_user.to_dict())

    data = {
        "follow_dict_li": follow_dict_li,
        "current_page": current_page,
        "total_page": total_page,

    }
    return render_template("news/user_follow.html", data=data)


@profile_blu.route('/news_list')
@query_user_data
def user_news_list():
    # 获取页数
    page = request.args.get("p", 1)

    try:
        page = int(page)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == g.user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS,
                                                                         False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())

    data = {
        "news_dict_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template('news/user_news_list.html', data=data)


@profile_blu.route('/news_release', methods=["POST", "GET"])
@query_user_data
def news_release():
    # 展示新闻分类
    if request.method == "GET":
        categories = []
        try:
            categories = Category.query.all()
        except Exception as f:
            current_app.logger.error(f)

        # 移除最新分类
        categories.pop(0)

        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())

        return render_template('news/user_news_release.html', data={"category_dict_li": category_dict_li})

    # 发布新闻

    # 获取参数
    source = "个人发布"
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")

    # print(type(index_image))
    content = request.form.get("content")

    # 校验参数
    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        category_id = int(category_id)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 取到图片, 将图片上传到七牛云
    try:
        index_image = index_image.read()
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        key = storage(index_image)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 初始化新闻模型
    news = News()
    news.source = source
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.content = content
    news.user_id = g.user.id
    # 代表待审核状态
    news.status = 1

    # 添加到数据库
    try:
        db.session.add(news)
        db.session.commit()

    except Exception as f:
        current_app.logger.error(f)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    return jsonify(errno=RET.OK, errmsg="发布成功, 等待审核中")


@profile_blu.route('/collection')
@query_user_data
def news_collection():
    """
    个人收藏新闻
    :return:
    """
    # 获取页数
    page = request.args.get("p", 1)

    # 校验参数
    try:
        page = int(page)
    except Exception as f:
        current_app.logger.error(f)

        page = 1

    user = g.user
    news_list = []
    current_page = 1
    total_page = 1

    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as f:
        current_app.logger.error(f)

    news_dict_li = []

    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "news_dict_li": news_dict_li,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/pass_info', methods=["POST", "GET"])
@query_user_data
def pass_info():
    """
    修改密码
    :return:
    """
    # 请求修改密码
    if request.method == "GET":
        return render_template('/news/user_pass_info.html')
    # 前端发来修改的数据
    # 1 获取参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    # 2 检验参数

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    user = g.user
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

    # 修改密码
    user.password = new_password

    return jsonify(errno=RET.OK, errmsg="操作成功")


@profile_blu.route('/pic_info', methods=["POST", "GET"])
@query_user_data
def pic_info():
    """
    修改头像
    :return:
    """
    user = g.user
    # 不同的请求方式做不同的事情
    if request.method == "GET":
        return render_template("news/user_pic_info.html", data={"user": user.to_dict()})

    # 用户用 POST 上传图片
    # 1. 取到用户上传的图像
    try:
        avatar = request.files.get("avatar").read()
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 2. 上传头像
    try:
        # 使用自己封装的方法 storage 去进行图片的上传
        key = storage(avatar)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.THIRDERR, errmsg="上传头像失败")

    # 3. 把图像路径保存到数据库
    user.avatar_url = key

    return jsonify(errno=RET.OK, errmsg="操作成功", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + key})


@profile_blu.route('/base_info', methods=["POST", "GET"])
@query_user_data
def base_info():
    """
    修改用户信息
    :return:
    """
    # 不同的请求方式做不同的事情
    if request.method == "GET":
        return render_template('news/user_base_info.html', data={"user": g.user.to_dict()})

    # 代表是用户修改数据
    # 1. 获取参数
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")

    # 2.校验参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    user = g.user

    user.nick_name = nick_name
    user.gender = gender
    user.signature = signature

    return jsonify(errno=RET.OK, errmsg="操作成功")


@profile_blu.route("/info")
@query_user_data
def user_info():
    """
    用户中心
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")
    data = {
        "user": user.to_dict()
    }
    return render_template("news/user.html", data=data)
